package com.sync.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sync.platform.common.Result;
import com.sync.platform.entity.DatabaseConfig;
import com.sync.platform.service.DatabaseConfigService;
import com.sync.platform.util.JdbcUrlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Database management controller
 */
@Controller
@RequestMapping("/database")
public class DatabaseController {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseController.class);

    @Autowired
    private DatabaseConfigService databaseConfigService;

    /**
     * Database list page
     */
    @GetMapping
    public String list(Model model) {
        LambdaQueryWrapper<DatabaseConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(DatabaseConfig::getCreateTime);
        model.addAttribute("databases", databaseConfigService.list(queryWrapper));
        model.addAttribute("pageTitle", "同步平台 - 数据库管理");
        return "database/list";
    }

    /**
     * Add database page
     */
    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("database", new DatabaseConfig());
        model.addAttribute("pageTitle", "同步平台 - 添加数据库");
        return "database/edit";
    }

    /**
     * Edit database page
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        DatabaseConfig database = databaseConfigService.getById(id);
        if (database == null) {
            return "redirect:/database";
        }

        model.addAttribute("database", database);
        model.addAttribute("pageTitle", "同步平台 - 编辑数据库");
        return "database/edit";
    }

    /**
     * Save database
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<?> save(@RequestBody DatabaseConfig databaseConfig) {
        boolean success = databaseConfigService.saveOrUpdate(databaseConfig);
        return success ? Result.success() : Result.fail("保存失败");
    }

    /**
     * Delete database
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public Result<?> delete(@PathVariable Long id) {
        boolean success = databaseConfigService.removeById(id);
        return success ? Result.success() : Result.fail("删除失败");
    }

    /**
     * Test database connection
     */
    @PostMapping("/test")
    @ResponseBody
    public Result<?> test(@RequestBody DatabaseConfig databaseConfig) {
        try {
            // Generate JDBC URL and driver class for the test
            if (databaseConfig.getDbType() != null && !databaseConfig.getDbType().isEmpty()) {
                if (databaseConfig.getUrl() == null || databaseConfig.getUrl().isEmpty()) {
                    String url = JdbcUrlBuilder.buildJdbcUrl(
                            databaseConfig.getDbType(),
                            databaseConfig.getHost(),
                            databaseConfig.getPort(),
                            databaseConfig.getDatabaseName(),
                            databaseConfig.getCharset()
                    );
                    databaseConfig.setUrl(url);
                }

                if (databaseConfig.getDriverClass() == null || databaseConfig.getDriverClass().isEmpty()) {
                    String driverClass = JdbcUrlBuilder.getDriverClassName(databaseConfig.getDbType());
                    databaseConfig.setDriverClass(driverClass);
                }
            }
            DatabaseConfig databaseConfigDb =  databaseConfigService.getDatabaseConfig(databaseConfig.getId());
            if (databaseConfigDb != null) {
                BeanUtils.copyProperties(databaseConfigDb, databaseConfig);
            }
            boolean success = databaseConfigService.testConnection(databaseConfig);
            if (success){
                databaseConfigService.updateStatus(databaseConfig.getId(), 1);
            }
            return success
                    ? Result.success("连接成功")
                    : Result.fail("连接失败，请检查数据库配置");
        } catch (Exception e) {
            logger.error("Error testing database connection: ", e);
            return Result.fail("连接失败: " + e.getMessage());
        }
    }

    /**
     * Update database status
     */
    @PutMapping("/{id}/status")
    @ResponseBody
    public Result<?> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        boolean success = databaseConfigService.updateStatus(id, status);
        return success ? Result.success() : Result.fail("更新状态失败");
    }

    /**
     * Get database tables
     */
    @GetMapping("/{id}/tables")
    @ResponseBody
    public Result<List<String>> getTables(@PathVariable Long id) {
        List<String> tables = databaseConfigService.getTables(id);
        return Result.success(tables);
    }

    /**
     * Get table columns
     */
    @GetMapping("/{id}/tables/{tableName}/columns")
    @ResponseBody
    public Result<List<Map<String, String>>> getColumns(@PathVariable Long id, @PathVariable String tableName) {
        List<Map<String, String>> columns = databaseConfigService.getColumns(id, tableName);
        return Result.success(columns);
    }

    /**
     * Execute query
     */
    @PostMapping("/{id}/query")
    @ResponseBody
    public Result<List<Map<String, Object>>> executeQuery(@PathVariable Long id, @RequestBody String sql) {
        List<Map<String, Object>> result = databaseConfigService.executeQuery(id, sql);
        return Result.success(result);
    }
}
